<script setup>

import MyNav from "../../../components/MyNav.vue";
import {onMounted, reactive, ref} from "vue";
import {getResponseData} from "../../../request/index.js";
import {DEFAULT_PASSWORD, insertApi, listApi} from "../../../api/axios.js";
import {ElMessage} from "element-plus";
import {RULE} from "../../../const/index.js";
import MyForm from "../../../components/MyForm.vue";
import router from "../../../router/index.js";

// 所在部门下拉菜单选项
let deptOptions = ref([]);

// 路径导航
const navItems = [
  {icon: 'Avatar', label: '用户管理', url: '/Emp'},
  {icon: 'User', label: '员工列表', url: '/Emp'},
  {icon: 'Plus', label: '添加新员工'},
];


// 表单项 + 表单值 + 表单规则
let items = ref([
  {label: '登录账号', prop: 'username', span: 12, required: true},
  {label: '真实姓名', prop: 'realname', span: 12, required: true},
  {label: '手机号码', prop: 'phone', span: 12, required: true},
  {label: '身份证号', prop: 'idcard', span: 12, required: true},
  {label: '微信号码', prop: 'wechat', span: 12, required: true},
  {label: '电子邮箱', prop: 'email', span: 12, required: true},
  {label: '所在部门', prop: 'fkDeptId', span: 12, required: true, type: 'select', options: deptOptions.value},
  {label: '入职日期', prop: 'hiredate', type: 'datetime', span: 12, required: true},
  {label: '现居住地', prop: 'address', required: true, type: 'textarea', rows: 2},
  {label: '员工描述', prop: 'info', type: 'textarea', rows: 6},

]);
let params = reactive({password: DEFAULT_PASSWORD});
let rules = {
  username: RULE.USERNAME,
  realname: RULE.REALNAME,
  phone: RULE.PHONE,
  idcard: RULE.IDCARD,
  email: RULE.EMAIL,
  address: RULE.ADDRESS
}

/* ======================================== 添加成功后 ================================================ */

function insertSuccess() {
  ElMessage.success('添加记录成功');
  setTimeout(() => router.push('/Emp'), 1000);
}

/* ======================================== 加载函数 ================================================ */

onMounted(async () => {
  // 查询全部部门，并添加到下拉菜单
  Object.values(getResponseData(await listApi({module: 'dept'}))).forEach(dept => {
    deptOptions.value.push({label: dept['title'], value: dept['id']});
  })
})
</script>

<template>
  <my-nav :items="navItems"/>
  <el-card class="emp-insert-card" header="添加新员工">
    <my-form type="insert"
             :items="items"
             :params="params"
             :rules="rules"
             :api="insertApi"
             :args="{module: 'emp'}"
             :callback="insertSuccess"/>
  </el-card>

</template>

<style scoped lang="scss">
.emp-insert-card {
  width: 60%; /// 宽度
  margin: 65px auto 0; // 外边距
}
</style>